package com.onion.auth.web.support;

import com.onion.auth.exception.AuthException;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class HttpRequestUtils {

    private static final String TOKEN_PARAM = "x-token";
    private static final String TOKEN_HEADER = "x-token";

    /**
     * 构建AuthContext
     * @param request
     * @return
     */
    public static HttpAclContext buildAuthContext(HttpServletRequest request){
        String xToken = getRequestToken(request);
        if(StringUtils.isNotBlank(xToken)){
            throw new AuthException(-5003, "Not Found the request token");
        }
        HttpAclContext authContext = new HttpAclContext();
        authContext.setRequestToken(xToken);
        authContext.setRequestResource(request.getRequestURI());
        return authContext;
    }

    /**
     * HTTP请求中获取请求Token
     * @param request
     * @return
     */
    public static String getRequestToken(HttpServletRequest request){
        String requestToken = request.getParameter(TOKEN_PARAM);
        if(StringUtils.isNotBlank(requestToken)){
            return requestToken;
        }
        return request.getHeader(TOKEN_HEADER);
    }

}